<?php
/**
 * PermissionService
 *
 * PHP Version 5.4
 *
 * @author liuxu <liuxuphp@icesmart.cn>
 */
namespace Admin\Service;
use Model\UserGroupFunctionModel;
use Model\UserGroupModel;
use Model\UserModel;
use Think\Controller;

/**
 * Class PermissionService
 */
class PermissionService extends Controller {

    /**
     * 验证用户功能权限
     */
    public function validate($userId, Array $module=[]){
        if(empty($userId) || empty($module)){
            $this->error('验证功能权限参数异常');
        }
        $permission = [];
        foreach($module as $k=>$v){
            $result = $this->process($userId, $v);
            $permission[$k] = $result;
        }
        
        return $permission;
    }

    /**
     * 处理结果
     */
    private function process($userId, $module)
    {
        $userModel = new UserModel();
        $userInfo = $userModel->get($userId);

        $userGroupModel = new UserGroupModel();
        $userGroupInfo = $userGroupModel->get($userInfo['groupId']);
        $groups = explode(' ', $userGroupInfo['functions']);

        $functionModel = new UserGroupFunctionModel();
        $functionInfo = $functionModel->buildQueryFilter(['url' => $module])->find();

        foreach($groups as $group){
            if($group == $functionInfo['id']){
                return true;
            }
        }
        return false;
    }

    /**
     * 显示菜单
     */
    public function menu($userId)
    {
        $userModel = new UserModel();
        $userInfo = $userModel->get($userId);

        $userGroupModel = new UserGroupModel();
        $userGroupInfo = $userGroupModel->get($userInfo['groupId']);
        $groups = explode(' ', $userGroupInfo['functions']);

        $functionModel = new UserGroupFunctionModel();
        $groupList = [];
        foreach($groups as $group){
            $groupList[] = $functionModel->get($group);
        }

        $categoryList = $functionModel->findByFilter(['categoryId' => 0], ['sort' => 'ASC']);

        $navMenu = [];
        foreach($categoryList as $category){
            foreach($groupList as $group){
                if($group['categoryId'] == $category['id'] && $group['isMenu'] == 1){
                    $navMenu[] = $group;
                }
            }
        }
        $menu['category'] = $categoryList;
        sort($navMenu);
        $menu['nav'] = $navMenu;
        foreach($menu['category'] as $k=>$v){
            $status = $this->isHasChildMenu($v['id'],$menu['nav']);
            if(!$status){
                unset($menu['category'][$k]);
            }
        }
        return $menu;
    }

    /**
     * @param $id
     * @param $menu
     */
    public function isHasChildMenu($id,$menu){
        foreach($menu as $k=>$v){
            if($v['categoryId'] == $id){
                return true;
            }
        }
        return false;
    }
}